package Servlst;

import db.Database;
import model.Uselogin;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(name = "LoginServlet1", value = "/Login1")
public class LoginServlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //统一编码格式
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();
        Connection conn = null;

        try {
            Database database = new Database();
            //使用方法调用验证账号密码是否正确
            Uselogin us = Database.login(username, password);
            if (us == null) {
                out.println("<script type='text/javascript' >alert('账号不存在或者密码错误!');</script>");
                out.println("<script>window.location='index.jsp'</script>");
            }
            else {
//                out.println("欢迎登录" + us.getUsername());
                //成功则跳转
                response.sendRedirect("Main.jsp");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            out.println("失败1");
        } catch (SQLException e) {
            out.println("失败2");
            e.printStackTrace();
        }
    }
}
